<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Cart;
use app\common\model\Coupon;
use app\common\model\coupon\Log;
use app\common\model\Order as ModelOrder;
use app\common\model\Shop;
use app\common\model\User;
use app\common\model\user\Address;
use app\common\model\Wxpay;
use think\Db;
use think\Queue;

/**
 * 订单接口
 */
class Order extends Api
{

    //如果$noNeedLogin为空表示所有接口都需要登录才能请求
    //如果$noNeedRight为空表示所有接口都需要验证权限才能请求
    //如果接口已经设置无需登录,那也就无需鉴权了
    //
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];


    /**
     * 订单购物车预付款下单
     *
     */
    public function yuOrder()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        $user_id = $this->auth->id;
        $ids = Cart::where('user_id', $user_id)->column('id');
        if (!isset($ids) || empty($ids)) {
            $this->error('购物车商品不存在');
        }
        if (!isset($shop_id) || empty($shop_id)) {
            $this->error('参数错误');
        }
        $shop = Shop::get(['status' => 'normal', 'state' => '1', 'id' => $shop_id]);
        if (!$shop) {
            $this->error('服务点为营业或不存在');
        }
        try {
            //获取购物车商品信息
            $goods = Cart::getGoods($ids, $user_id);
            if (!$goods) {
                exception('请先选择商品');
            }
            $total_money =  $pay_money = array_sum(array_column($goods, 'total'));
            $pay_num = array_sum(array_column($goods, 'num'));
            if (isset($address_id) && !empty($address_id)) {
                $addressInfo = Address::get($address_id);
                $data['address_info'] = $addressInfo;
                $data['address_id'] = $address_id;
            } else {
                $addressInfo = Address::getDefaultAddress($user_id);
                if ($addressInfo) {
                    $data['address_info'] = $addressInfo;
                    $data['address_id'] = $addressInfo['id'];
                }
            }
            $log = new Log();

            if (isset($coupon_id) && $coupon_id) {
                $coupon = Log::get($coupon_id);
                $discount_amount = Log::useCoupon($pay_money, $coupon_id, $user_id);
            } else {
                $coupon = $log->useMaxCoupon($pay_money, $user_id);
                if ($coupon) {
                    $discount_amount = Log::useCoupon($pay_money, $coupon['id'], $user_id);
                }
            }

            $data['total_amount'] = $total_money;
            $data['pay_price'] = bcsub($pay_money, ($discount_amount ?? 0), 2);
            $data['discount_amount'] = $discount_amount ?? 0;
            $data['goods'] = $goods;
            $data['coupon'] = $coupon;
            $data['shop_id'] = $shop_id;
            $data['coupon_id'] = $coupon_id ?? 0;
            $data['goods_num'] = $pay_num;
            cache('order_' . $user_id, $data, '900');
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('', $data);
    }

    /**
     * 订单统一下单
     *
     */
    public function addOrder()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $post = request()->post();
        extract($post);
        $uid = $this->auth->id;
        $data = cache('order_' . $uid);
        if (!$data) {
            $this->error('订单已失效，请重新选择商品');
        }
        if (!isset($data['address_id']) || empty($data['address_id'])) {
            $this->error('收货地址不能为空');
        }
        if (isset($content) && $content) {
            $data['content'] = $content;
        }
        Db::startTrans();
        try {
            //添加订单商品信息
            $order = new ModelOrder();
            $order_id = $order->addData($data,  $uid);
            if (!$order_id) {
                exception('下单失败');
            }
            log::where('id', $data['coupon_id'])->update(['state' => 2]);
            $total_order = ModelOrder::get($order_id);
            // $userInfo = User::get($uid);
            // $res =  Wxpay::wxpay($total_order->sn, $data['pay_price'], $userInfo['openid'], 'order');
            Cart::delCart($uid);
            //加入队列

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return self::error($e->getMessage());
        }
        Queue::later(900, 'app\common\job\Order', $total_order, 'order');
        cache('order_' . $uid, null);
        return $this->success('下单成功', $order_id);
    }

    /**
     * 立即付款
     *
     */
    public function pay()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        $order = ModelOrder::get($id);

        if ($order['pay_money'] <= 0) {
            $res = $order->save(['status' => 1, 'paytime' => time()]);
            if ($res)
                $this->success('支付成功', '', 200);
            else
                $this->error('支付失败');
        } else {
            $uid = $this->auth->id;
            $userInfo = User::get($uid);
            $list = Wxpay::wxpay($order->sn, $order['pay_money'], $userInfo['openid'], 'order');
            $this->success('获取成功', $list);
        }
    }
    /**
     * 取消订单
     *
     */
    public function cancel()
    {
        if (!$this->request->isPost()) {
            $this->error('提交类型错误');
        }
        $id = $this->request->post('id');
        if (!isset($id) || empty($id)) {
            $this->error('参数错误');
        }
        Db::startTrans();
        try {
            $order = new ModelOrder;
            $order =  $order->get($id);
            $res = $order->save(['status' => '-1', 'canceltime' => time()]);
            if ($order['coupon_id'] && $res) {
                Log::where('id', $order['coupon_id'])->update(['state' => 1]);
            }
            // Wxpay::refund($id);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollback();
            $this->error('取消失败:' . $e->getMessage());
        }
        $this->success('取消成功');
    }

    /**
     * 我的订单
     *
     */
    public function list()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if (!isset($type) || empty($type)) {
            $this->error('参数错误');
        }
        //待付款
        if ($type == 1) {
            $where['order.status'] = ['=', '0'];
        }
        //待付款
        if ($type == 2) {
            $where['order.status'] = ['=', '1'];
        }
        //清洗中
        if ($type == 3) {
            $where['order.status'] = ['in', ['2', '3', '4', '5', '6']];
        }
        //待取回
        if ($type == 4) {
            $where['order.status'] = ['=', '7'];
        }
        //已完成
        if ($type == 5) {
            $where['order.status'] = ['=', '8'];
        }
        $order = ModelOrder::with(['goods', 'user', 'shop'])->where($where)->where('order.user_id', $this->auth->id)->order('createtime desc')->paginate(10);

        return $this->success('获取成功', $order);
    }
    /**
     * 订单详情
     *
     */
    public function info()
    {
        if (!$this->request->isGet()) {
            $this->error('提交类型错误');
        }
        $get = $this->request->get();
        extract($get);
        if ((!isset($id) || empty($id)) && (!isset($sn) || empty($sn))) {
            $this->error('参数错误');
        }
        if (isset($id) && $id) {
            $where['order.id'] = $id;
        }
        if (isset($sn) && $sn) {
            $where['bar_code'] = $sn;
        }
        $order = new ModelOrder();
        $data = $order->get($where, ['goods', 'address', 'pickInfo', 'cleanInfo', 'shop', 'retrieveInfo']);
        $this->success('返回成功', $data);
    }
}
